<?php

class Application_Model_NewsMapper{
	
	protected $_dbTable;
	
	public function setDbTable($dbTable){
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}
	
	public function getDbTable(){
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_News');
		}
		return $this->_dbTable;
	}
	public function save(Application_Model_News $news){
		$data = array(
			'title' 	=> $news->getTitle(),
			'author'	=> $news->getAuthor(),
			'text'		=> $news->getText()
		);
		
		if(null ===($id=$news->getId())){
			unset($data['id']);
			$data['date'] = new Zend_Db_Expr('NOW()');
			$this->getDbTable()->insert($data);
		} else {
			unset($data['author']);
			unset($data['date']);
			$this->getDbTable()->update($data, array('id = ?' => $id));
		}
	}
	public function find($id, Application_Model_News $news){
		$result = $this->getDbTable()->find($id);
		if(count($result)==0){
			return;
		}
		$row = $result->current();
		$news	->setId($row->id)
				->setAuthor($row->author)
				->setDate($row->date)
				->setText($row->text)
				->setTitle($row->title);
		return $news;
	}
	public function fetchAll(){
		$resultSet = $this->getDbTable()->fetchAllWithAuthor();
		$entries = array();
		foreach($resultSet as $row){
			$entry = new Application_Model_News();
			$entry	->setId($row->id)
					->setAuthor($row->author)
					->setDate($row->date)
					->setText($row->text)
					->setPseudo($row->pseudo)
					->setTitle($row->title);
			$entries[] = $entry;
		}
		return $entries;
	}
	public function delete($id){
		$comDB = new Application_Model_DbTable_Comment();
		$comDB->deleteCommentByPost($id);
		$this->getDbTable()->deleteNews($id);
	}
}